import { fb_join_group_main, getRandomArbitrary, addFbGroupCountObjStore, shouldSkipJoinGroup } from "../fb_join_group_main.js"
import { arrayToValueOfConfig, sendAutomationMessage } from "../../../utils/index.js"
import { openWindowData, closeWindowData } from "../../../api/adsApi/index.js"
import pLimit from "p-limit"
import { windowIdOfTask } from "../../../config/index.js"
import { puppeteer } from "../../../utils/puppeteer-adapter.js"
export const fb_join_group = async (task, windowIndex, headless) => {
  console.log("开始加入社群")
  return new Promise(async (resolve, reject) => {
    // 获取平台名称
    let platformName = task[0].platformName
    // 获取租户id
    let tenantId = task[0]?.tenantId
    // 获取deptId
    let deptId = task[0]?.deptId
    // 获取taskId
    let taskId = task[0]?.taskId
    const publishPostParams = {
      platformName: platformName,
      tenantId: tenantId,
      deptId: deptId,
      taskId: taskId,
    }
    console.log("publishPostParams===>", publishPostParams)
    const startTime = Date.now()
    let successCount = 0
    let failureCount = 0

    const limit = pLimit(1)
    let browser = null
    const failedAccount = []
    try {
      // 执行任务
      const taskPromises = task.map((singleTask, index) => {
        return new Promise(async (resolveTask, rejectTask) => {
          try {
            await limit(async () => {
              const userId = singleTask.deviceId
              try {
                console.log(`窗口 ${windowIndex + 1} 开始处理加入社群任务 ${singleTask.account} 指定账号加入社群任务`)
                const composedTask = singleTask.composedTask
                // 获取运行配置
                const config = composedTask.config || []
                // 读取配置参数
                // 每日添加群组
                const addGroupDayCount = arrayToValueOfConfig(config, "add_group_day_count")
                // 账号添加群组总数
                const addGroupLimitCount = arrayToValueOfConfig(config, "add_group_limit_count")
                // 根据本地缓存。计算一下今天添加的群组数是否超过配置数
                // 在根据本地缓存，计算一下该账号总共添加的群组数量
                const addGroupObj = {
                  addGroupDayCount,
                  addGroupLimitCount,
                }
                // 直接先判断任务是否需要执行
                const shouldSkip = await shouldSkipJoinGroup(singleTask.account, addGroupObj)
                if (shouldSkip) {
                  console.log("当前任务已不满足执行条件，跳过")
                  return resolve(true)
                }
                const addGroupMaxCount = `facebook_add_total_count_${singleTask.account}`
                // 判断配置数量是否小于已添加的小组总数
                if (addFbGroupCountObjStore.get(addGroupMaxCount) >= addGroupLimitCount) {
                  // 已添加的小组总数大于等于配置的最大限制，则不再执行
                  console.log("已添加的小组总数大于等于配置的最大限制，则不再执行")
                  return resolve(true)
                } else {
                  // 未达到限制，则执行任务
                  // 重置已添加最大限制数为0
                  addFbGroupCountObjStore.set(addGroupMaxCount, 0)
                }
                // 判断一下数量是否超出限制
                // 使用重试机制打开浏览器
                const openBrowserResponse = await retryOperation(async () => {
                  console.log(`尝试连接AdsPower服务，userId: ${userId}, headless: ${headless}`)

                  // 检查AdsPower服务是否可用
                  try {
                    await new Promise((resolve) => setTimeout(resolve, 1000))
                    // 使用限流控制的函数替代直接调用fetch
                    // const checkResult = await checkBrowserActive(userId);
                    // 不需要再次输出日志，checkBrowserActive已经处理了
                  } catch (error) {
                    console.error("AdsPower服务不可用:", error.message)
                    throw new Error(`AdsPower服务不可用: ${error.message}`)
                  }

                  return await openWindowData({ userId, headless })
                })

                console.log("AdsPower API响应:", JSON.stringify(openBrowserResponse, null, 2))

                // 检查API响应是否成功
                if (!openBrowserResponse || !openBrowserResponse.data || !openBrowserResponse.data.ws) {
                  throw new Error(`无法获取浏览器窗口: ${JSON.stringify(openBrowserResponse)}`)
                }

                const wsEndpoint = openBrowserResponse.data.ws.puppeteer
                console.log(`成功获取WebSocket端点: ${wsEndpoint}`)

                // 使用重试机制连接浏览器
                browser = await retryOperation(async () => {
                  return await puppeteer.connect({ browserWSEndpoint: wsEndpoint, defaultViewport: null })
                })

                console.log("成功连接到浏览器")

                // 窗口id绑定taskId
                if (!windowIdOfTask[taskId]) {
                  windowIdOfTask[taskId] = []
                }
                if (!windowIdOfTask[taskId].find((v) => v == userId)) {
                  windowIdOfTask[taskId].push(userId)
                  console.log("windowIdOfTask[taskId]==>3", windowIdOfTask[taskId])
                }
                await fb_join_group_main(singleTask, browser, index, taskId, publishPostParams)
                // 运行发帖任务
                successCount++
                resolveTask({
                  success: true,
                  deviceId: userId,
                  account: singleTask.account,
                  message: `账号 ${singleTask.account} 发帖成功`,
                })
              } catch (error) {
                console.error(`窗口 ${windowIndex + 1} 账号 ${singleTask.account} 处理失败:`, error)
                failureCount++
                failedAccount.push(singleTask)
                rejectTask({
                  success: false,
                  deviceId: userId,
                  account: singleTask.account,
                  error: error.message || "发帖任务失败",
                })
              }
            })
          } catch (error) {
            failureCount++
            rejectTask({
              success: false,
              account: singleTask.account,
              error: error.message || "执行发帖任务时出错",
            })
          }
        }).catch((error) => {
          console.error(`账号 ${singleTask.account || "未知"} 发帖任务异常:`, error)
          return { success: false, error: error.message }
        })
      })

      // 等待所有任务完成，即使某些任务失败也会继续
      const results = await Promise.allSettled(taskPromises)

      console.log(`发帖任务执行结果:`, results.map((r) => r.status).join(", "))

      // 重试失败任务
      if (failedAccount.length > 0) {
        console.log(`窗口 ${windowIndex + 1} 开始重试 ${failedAccount.length} 个失败任务`)

        const retryPromises = failedAccount.map((failedTask, index) => {
          return new Promise(async (resolveRetry, rejectRetry) => {
            try {
              await limit(async () => {
                const userId = failedTask.deviceId
                console.log(`重试账号 ${failedTask} 发帖任务`)

                // 使用重试机制打开浏览器
                let localBrowser = null
                try {
                  const openBrowserResponse = await retryOperation(async () => {
                    return await openWindowData({ userId, headless })
                  })

                  if (!openBrowserResponse?.data?.ws) {
                    throw new Error(`重试时无法获取浏览器窗口`)
                  }

                  // 在连接浏览器之前，先检查它是否处于活动状态
                  try {
                    // 使用限流控制的函数替代直接调用fetch
                    // const checkResult = await checkBrowserActive(userId);
                  } catch (error) {
                    console.error("AdsPower服务不可用:", error.message)
                    throw new Error(`AdsPower服务不可用: ${error.message}`)
                  }

                  localBrowser = await puppeteer.connect({
                    browserWSEndpoint: openBrowserResponse.data.ws.puppeteer,
                    defaultViewport: null,
                  })

                  await fb_join_group_main(failedTask, localBrowser, index, taskId, publishPostParams)
                  // 重试成功
                  successCount++
                  resolveRetry({
                    success: true,
                    deviceId: userId,
                    account: failedTask.account,
                    message: `账号 ${failedTask.account} 重试发帖成功`,
                  })
                } catch (error) {
                  console.error(`重试账号 ${failedTask} 发帖任务仍然失败:`, error)
                  failureCount++
                  rejectRetry({
                    success: false,
                    deviceId: userId,
                    account: failedTask.account,
                    error: error.message || "重试发帖任务失败",
                  })
                } finally {
                  if (localBrowser) {
                    try {
                      await localBrowser.close()
                    } catch (err) {}
                    localBrowser = null
                  }
                }
              })
            } catch (error) {
              rejectRetry({
                success: false,
                deviceId: failedTask.deviceId,
                account: failedTask.account,
                error: error.message || "执行重试发帖任务时出错",
              })
            }
          }).catch((error) => {
            // 捕获并记录重试错误，但允许其他重试继续
            console.error(`账号 ${failedTask.account} 重试发帖失败:`, error)
            return { success: false, error: error.message }
          })
        })

        // 等待所有重试完成
        const retryResults = await Promise.allSettled(retryPromises)
        console.log(`重试发帖结果:`, retryResults.map((r) => r.status).join(", "))
      }

      const duration = ((Date.now() - startTime) / 1000).toFixed(2)
      console.log(`窗口 ${windowIndex + 1} 处理完成，总成功: ${successCount}, 总失败: ${failureCount}, 用时: ${duration} 秒`)

      // 安全关闭浏览器
      if (browser) {
        try {
          await browser.close()
          console.log(`窗口 ${windowIndex + 1} 浏览器已关闭`)
        } catch (error) {
          console.error(`窗口 ${windowIndex + 1} 关闭浏览器时出错:`, error)
        }
      }

      // 成功完成任务，返回结果
      resolve({
        success: true,
        successCount,
        failureCount,
        duration,
        message: `窗口 ${windowIndex + 1} 处理完成，总成功: ${successCount}, 总失败: ${failureCount}, 用时: ${duration} 秒`,
      })
    } catch (error) {
      // 开启窗口异常。需要汇报
      console.error(`窗口 ${windowIndex + 1} 异常:`, error)

      // 尝试安全关闭浏览器
      if (browser) {
        try {
          await browser.close()
          console.log(`窗口 ${windowIndex + 1} 浏览器已关闭`)
        } catch (closeError) {
          console.error(`窗口 ${windowIndex + 1} 关闭浏览器时出错:`, closeError)
        }
      }
      sendAutomationMessage("send-node-error", `id：${task[0]?.deviceId || "未知"} 窗口异常。请检查窗口id是否正确。`)

      // 任务失败，通过reject返回错误
      reject({
        success: false,
        error: error.message || "发帖任务执行失败",
        deviceId: task[0]?.deviceId || "未知",
        successCount,
        failureCount,
      })
    }
  })
}
/**
 * 添加重试函数
 * @param {Function} operation - 要重试的操作函数
 * @param {number} maxRetries - 最大重试次数，默认为3
 * @param {number} delay - 重试间隔，默认为1000毫秒
 * @returns {Promise<any>} - 返回操作结果
 */
async function retryOperation(operation, maxRetries = 3, delay = 1000) {
  let lastError
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await operation()
    } catch (error) {
      lastError = error
      console.error(`操作失败 (尝试 ${i + 1}/${maxRetries}):`, error.message)
      if (i < maxRetries - 1) {
        console.log(`等待 ${delay}ms 后重试...`)
        await new Promise((resolve) => setTimeout(resolve, delay))
      }
    }
  }
  throw lastError
}

